Everything in python are objects
Objects are instances of classes
In [4]:
class Student(object):
def __init__(self, nameInput):
self.name = nameInput
In [6]:
student1 = Student('Casey')
In [7]:
student1.name
Out[7]:
Student is a class By convention, use captilization
student1 is an object student1 is the instance of the class Student
Classes have attributes Attributes are like data
init is used to initialize object attributes self refers to the instantiated object
By convention, the above is usually defined as
In [8]:
class Student(object):
def __init__(self,name):
self.name = name
# note how nameInput has been changed to name
In [22]:
student1 = Student('Casey')
print student1.name
In [23]:
student2 = Student(name='Varma')
print student2.name
In [19]:
class Rectangle(object):
def __init__(self, height, width):
self.height = height
self.width = width
def area(self):
return self.height*self.width
In [24]:
rect1 = Rectangle(1,2)
print 'Area is', rect1.area()
In [21]:
class Circle(object):
pi = 3.14
# Circle get instantiated with a radius (default is 1)
def __init__(self, radius=1):
self.radius = radius
# Area method calculates the area. Note the use of self.
def area(self):
return self.radius * self.radius * Circle.pi
# Method for resetting Radius
def setRadius(self, radius):
self.radius = radius
# Method for getting radius (Same as just calling .radius)
def getRadius(self):
return self.radius
c = Circle()
c.setRadius(2)
print 'Radius is: ',c.getRadius()
print 'Area is: ',c.area()
In [25]:
class Student(object):
# class object attribute
college = 'A&M'
def __init__(self,name):
self.name = name
In [26]:
student3 = Student('Rahman')
print student3
print student3.name
print student3.college
In [42]:
class Animal(object):
def __init__(self):
print 'Animal created'
def whoAmI(self):
print 'Animal'
def eat(self):
print 'Eating'
def __del__(self):
print 'del is a standard python object'
print 'Here del is used as a special method'
print 'Animal destroyed'
In [43]:
anim1 = Animal()
print anim1.whoAmI()
print anim1.eat()
del anim1
strangely 'None' is getting printed. This is due to not returning in methods function call
Check stackoverflow discussion Also Tips on markdown
Anyways, here is a derived class
In [45]:
class Dog(Animal):
def __init__(self):
print 'Dog created'
def bark(self):
return "Woff woof"
def whoAmI(self):
print 'I am a dog.'
return 'Did you expect Animal to print?'
dog1 = Dog()
print dog1.bark()
print dog1.whoAmI()
print dog1.eat()
In [47]:
print 'GOOD luck!'
In [ ]: